package com.tvunetworks.center.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.tvunetworks.center.common.model.LoginUser;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.common.util.ResultUtil;
import com.tvunetworks.center.user.annotation.Logined;
import com.tvunetworks.center.user.model.vo.ExtBindReceiverVo;
import com.tvunetworks.center.user.service.ExtService;
import com.tvunetworks.center.user.service.feign.DeviceFeignService;
import com.tvunetworks.center.user.util.ExcelImport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @program: tvucc-user
 * @description: ExtController
 * @author lebronchen
 * @create: 2019-03-19 14:03
 **/
@RestController
@RequestMapping("/ext")
public class ExtController {

    @Autowired
    private ExtService extService;
    @Autowired
    private DeviceFeignService deviceFeignService;
    /**
     * @param loginUser loginUser
     * @param name name
     * @param url url
     * @param type type
     * @param rid 如果rid存在表示需要把Ext下发到R上
     * @return Result
     * @param remark remark
     */
    @PostMapping("/addExt")
    public Result<String> addExt(@Logined LoginUser loginUser, @RequestParam String name, @RequestParam String url, @RequestParam String type, String rid,String remark){
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        return extService.addExtToUserByCC(loginUser, name, url, type, rid,remark);
    }

    /**
     *
     * @param peerId peerId
     * @param name name
     * @param url url
     * @param remark remark
     * @return Result
     */
    @PostMapping("/updateExt")
    public Result<String> updateExt(@RequestParam String peerId, @RequestParam String name, @RequestParam String url,String remark){

        return extService.updateExt(peerId, name, url,remark);
    }

    /**
     *
     * @param peerId peerId
     * @return Result
     */
    @PostMapping("/deleteExt")
    public Result<String> deleteExt(@RequestParam String peerId){
        return extService.deleteExt(peerId);
    }

    /**
     *
     * @param loginUser loginUser
     * @param peerId peerId
     * @param condition condition
     * @return Result
     */
    @GetMapping("/listExtBindedRids")
    public Result<Object> listExtBindedRids(@Logined LoginUser loginUser, @RequestParam String peerId, String condition) {
        if (loginUser == null){
            return ResultUtil.noLogin();
        }
        List<ExtBindReceiverVo> list = extService.listExtBindedRids(loginUser.getId(), peerId, condition);
        return ResultUtil.success(list);
    }

    /**
     *
     * @param loginUser loginUser
     * @param peerId peerId
     * @param condition condition
     * @return Result
     */
    @GetMapping("/listExtUnBindRids")
    public Result<Object> listExtUnBindRids(@Logined LoginUser loginUser, @RequestParam String peerId, String condition) {
        if (loginUser == null){
            return ResultUtil.noLogin();
        }
        List<ExtBindReceiverVo> list = extService.listExtUnBindRids(loginUser.getId(), peerId, condition);
        return ResultUtil.success(list);
    }

    /**
     *
     * @param data data
     * @return Result
     */
    @PostMapping("/correlateExtPairedR")
    public Result<Object> correlateExtPairedR(@RequestBody JSONObject data) {
        String peerId = data.getString("peerId");
        String addRids = data.getString("addRids");
        String removeRids = data.getString("removeRids");
        extService.correlateExtPairedR(peerId, addRids, removeRids);
        return ResultUtil.success();
    }

//    @PostMapping("/importFile")

    /**
     *
     * @param loginUser loginUser
     * @param file file
     * @param request request
     * @return Result
     * @throws Exception 编译异常
     */
    public Result<Object> importExcel(@Logined LoginUser loginUser,@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
//    public Result<Object> importExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
//        if (loginUser == null){
//            return ResultUtil.noLogin();
//        }
//        LoginUser loginUser = new LoginUser();
//        loginUser.setId("8a8c96d951320921015133dac5790003");
        //获取用户上传表格的地址，执行完程序后表格将会删除，避免占用内存
        String filePath = request.getSession().getServletContext().getRealPath("/");
        //根据地址和文件名准确获取用户上传的表格
        File tempFile = new File(filePath + file.getOriginalFilename());
        List successName = new ArrayList();
        try {
            //将MultipartFile转换为File类型
            file.transferTo(tempFile);
            List<Map<Integer, String>> dataList = ExcelImport.read(tempFile, 2);

            for (int i = 0; i < dataList.size(); i++) {
                //此处的取值顺序取决于Excel表的表头顺序，一一对应
                String url = dataList.get(i).get(0);
                int index = url.lastIndexOf("/");
//              String before = url.substring(0,index + 1);
                String name = url.substring(index + 1);
                String remark = dataList.get(i).get(1);
                Result<String>  result =  extService.addExtToUser(loginUser, name,url, "FILE", null,remark);
                if(result.getErrorCode().contains("81000101")){
                    if(name.contains(".")){

                        int indexD = name.lastIndexOf(".");
                        String nameBef = name.substring(0,indexD);
                        String nameAft = name.substring(indexD);
                        String uuid = UUID.randomUUID().toString();
                        name = nameBef+"_"+uuid.substring(0,3)+uuid.substring(uuid.length()-3)+nameAft;
                    }
                    extService.addExtToUser(loginUser, name,url, "FILE", null,remark);
                }
                successName.add(name);
            }
            //执行完程序后删除用户上传文件
            boolean delete = tempFile.delete();
            System.out.println(delete);
        } catch (Exception e) {
            boolean delete = tempFile.delete();
            System.out.println(delete);
            return ResultUtil.error("81000701",e.getMessage());

        }
            return ResultUtil.success().setResult("Success:"+JSONObject.toJSONString(successName));
    }

}
